<template>
  <div class="login-container relative min-h-screen flex items-center justify-center overflow-hidden bg-gradient-to-b from-sky-50 to-white">
    <!-- 背景装饰 -->
    <div class="absolute top-0 right-0 w-64 h-64 bg-indigo-100 rounded-full filter blur-3xl opacity-30 -translate-y-1/2 translate-x-1/3"></div>
    <div class="absolute bottom-0 left-0 w-80 h-80 bg-sky-100 rounded-full filter blur-3xl opacity-20 translate-y-1/3 -translate-x-1/3"></div>

    <!-- 登录/注册卡片（支持模式切换） -->
    <div class="relative z-10 w-full max-w-md bg-white rounded-lg shadow-lg border border-sky-50 overflow-hidden transform transition-all duration-500">
      <!-- 系统标题区 -->
      <div class="py-5 text-center bg-gradient-to-r from-sky-500 to-indigo-600 text-white">
        <h1 class="text-xl font-bold flex items-center justify-center">
          <font-awesome-icon icon="file-contract" class="mr-2" />
          电子合同标准化云平台系统
        </h1>
      </div>
      
      <div class="p-8">
        <!-- 登录/注册标题 -->
        <div class="text-center mb-8">
          <h2 class="text-xl font-semibold text-gray-800 flex items-center justify-center">
            <span class="w-1 h-6 bg-gradient-to-b from-sky-500 to-indigo-600 rounded-full mr-3"></span>
            {{ isRegisterMode ? '用户注册' : '用户登录' }}
          </h2>

          <!-- 登录表单（默认显示） -->
          <div v-if="!isRegisterMode">
            <!-- 用户名输入框 -->
            <div class="relative mb-5">
              <div class="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400">
                <i class="fa fa-user"></i>
              </div>
              <input
                  type="text"
                  v-model="username"
                  class="w-full px-3 py-2 pl-10 border border-sky-100 rounded-md focus:outline-none focus:ring-2 focus:ring-sky-500 focus:border-transparent transition-all"
                  placeholder="用户名"
                  :disabled="isLoading"
              >
            </div>

            <!-- 密码输入框 -->
            <div class="relative mb-6">
              <div class="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400">
                <i class="fa fa-lock"></i>
              </div>
              <input
                  :type="showPassword ? 'text' : 'password'"
                  v-model="password"
                  class="w-full px-3 py-2 pl-10 pr-10 border border-sky-100 rounded-md focus:outline-none focus:ring-2 focus:ring-sky-500 focus:border-transparent transition-all"
                  placeholder="密码"
                  :disabled="isLoading"
              >
              <button
                  type="button"
                  @click="showPassword = !showPassword"
                  class="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600 transition-colors"
                  :disabled="isLoading"
              >
                <i class="fa" :class="showPassword ? 'fa-eye-slash' : 'fa-eye'"></i>
              </button>
            </div>

            <!-- 忘记密码链接（仅登录显示） -->
            <div class="flex justify-end mb-6">
              <a href="#" class="text-sky-600 hover:text-sky-800 text-sm transition-colors">忘记密码?</a>
            </div>

            <!-- 登录按钮 -->
            <button
                @click="handleLogin"
                class="w-full bg-gradient-to-r from-sky-500 to-indigo-600 text-white font-medium py-2.5 rounded-md hover:from-sky-600 hover:to-indigo-700 transition-all shadow-sm hover:shadow"
                :disabled="isLoading"
            >
              <span v-if="!isLoading">登录</span>
              <span v-if="isLoading" class="flex items-center justify-center">
                <i class="fa fa-spinner fa-spin mr-2"></i> 处理中...
              </span>
            </button>

            <!-- 切换到注册的链接 -->
            <div class="text-center mt-4 text-sm">
              <span class="text-gray-600">没有账号？</span>
              <button
                  type="button"
                  @click="isRegisterMode = true"
                  class="text-sky-600 hover:text-sky-800 ml-1 transition-colors"
                  :disabled="isLoading"
              >
                去注册
              </button>
            </div>
          </div>

          <!-- 注册表单（切换显示） -->
          <div v-else>
            <!-- 用户名输入框（注册用） -->
            <div class="relative mb-5">
              <div class="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400">
                <i class="fa fa-user"></i>
              </div>
              <input
                  type="text"
                  v-model="username"
                  class="w-full px-3 py-2 pl-10 border border-sky-100 rounded-md focus:outline-none focus:ring-2 focus:ring-sky-500 focus:border-transparent transition-all"
                  placeholder="设置用户名（至少2个字符）"
                  :disabled="isLoading"
              >
            </div>

            <!-- 密码输入框（注册用） -->
            <div class="relative mb-5">
              <div class="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400">
                <i class="fa fa-lock"></i>
              </div>
              <input
                  :type="showPassword ? 'text' : 'password'"
                  v-model="password"
                  class="w-full px-3 py-2 pl-10 pr-10 border border-sky-100 rounded-md focus:outline-none focus:ring-2 focus:ring-sky-500 focus:border-transparent transition-all"
                  placeholder="设置密码（至少6个字符）"
                  :disabled="isLoading"
              >
              <button
                  type="button"
                  @click="showPassword = !showPassword"
                  class="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600 transition-colors"
                  :disabled="isLoading"
              >
                <i class="fa" :class="showPassword ? 'fa-eye-slash' : 'fa-eye'"></i>
              </button>
            </div>

            <!-- 确认密码输入框（仅注册显示） -->
            <div class="relative mb-6">
              <div class="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400">
                <i class="fa fa-key"></i>
              </div>
              <input
                  :type="showPassword ? 'text' : 'password'"
                  v-model="confirmPassword"
                  class="w-full px-3 py-2 pl-10 pr-10 border border-sky-100 rounded-md focus:outline-none focus:ring-2 focus:ring-sky-500 focus:border-transparent transition-all"
                  placeholder="确认密码"
                  :disabled="isLoading"
              >
            </div>

            <!-- 注册按钮 -->
            <button
                @click="handleRegister"
                class="w-full bg-gradient-to-r from-sky-500 to-indigo-600 text-white font-medium py-2.5 rounded-md hover:from-sky-600 hover:to-indigo-700 transition-all shadow-sm hover:shadow"
                :disabled="isLoading"
            >
              <span v-if="!isLoading">注册</span>
              <span v-if="isLoading" class="flex items-center justify-center">
                <i class="fa fa-spinner fa-spin mr-2"></i> 注册中...
              </span>
            </button>

            <!-- 切换到登录的链接 -->
            <div class="text-center mt-4 text-sm">
              <span class="text-gray-600">已有账号？</span>
              <button
                  type="button"
                  @click="isRegisterMode = false"
                  class="text-sky-600 hover:text-sky-800 ml-1 transition-colors"
                  :disabled="isLoading"
              >
                去登录
              </button>
            </div>
          </div>
        </div>

        <!-- 其他登录方式（仅登录模式显示） -->
        <div v-if="!isRegisterMode && !isLoading" class="mt-8">
          <div class="relative flex items-center justify-center mb-6">
            <div class="w-1/3 h-px bg-gray-200"></div>
            <span class="mx-4 text-gray-500 text-sm">其他登录方式</span>
            <div class="w-1/3 h-px bg-gray-200"></div>
          </div>

          <div class="flex justify-center space-x-6">
            <button class="w-10 h-10 rounded-full bg-sky-50 border border-sky-100 flex items-center justify-center text-sky-600 hover:bg-sky-100 transition-all">
              <font-awesome-icon icon="fab fa-weixin" class="text-lg" />
            </button>
            <button class="w-10 h-10 rounded-full bg-sky-50 border border-sky-100 flex items-center justify-center text-sky-600 hover:bg-sky-100 transition-all">
              <font-awesome-icon icon="fab fa-qq" class="text-lg" />
            </button>
            <button class="w-10 h-10 rounded-full bg-sky-50 border border-sky-100 flex items-center justify-center text-sky-600 hover:bg-sky-100 transition-all">
              <font-awesome-icon icon="fab fa-weibo" class="text-lg" />
            </button>
          </div>
        </div>
      </div>

      <!-- 底部版权信息 -->
      <div class="bg-gray-50 py-4 px-6 text-center text-gray-500 text-xs border-t border-sky-50">
        <p>© 2023 合同管理系统 版权所有</p>
        <p class="mt-1">服务热线: 400-123-4567</p>
      </div>
    </div>
  </div>
</template>

<script> import {loginApi, registerApi} from "@/api/user";

export default {
  name: 'LoginRegister',
  data() {
    return {
      username: '',
      password: '',
      confirmPassword: '', // 新增：注册确认密码
      showPassword: false,
      isLoading: false,
      isRegisterMode: false // 新增：控制登录/注册模式切换
    }
  },
  methods: {
    async handleLogin() {
      // 表单验证
      if (!this.username || !this.password) {
        alert('请输入用户名和密码')
        return
      }
      if (this.username.length < 2) {
        alert('用户名至少2个字符')
        return
      }
      if (this.password.length < 6) {
        alert('密码至少6个字符')
        return
      }

      this.isLoading = true

      try {
        const res = await loginApi({
          username: this.username,
          password: this.password
        })

        if (res.code === 200) {
          // 登录成功：存储 token 和用户信息
          localStorage.setItem('token', res.data.token)
          localStorage.setItem('userInfo', JSON.stringify(res.data.user))

          // 更新全局用户信息（如果使用了Vuex或其他状态管理）
          // 这里通过事件总线或直接刷新页面来确保其他组件获取到最新的用户信息
          window.dispatchEvent(new Event('user-login'));

          alert('登录成功！')
          setTimeout(() => {
            this.$router.push('/')
          }, 500)
        } else {
          alert(res.msg || '登录失败')
        }
      } catch (error) {
        console.error('登录异常:', error)
        alert('网络错误，请稍后重试')
      } finally {
        this.isLoading = false
      }
    },

    // 新增：注册逻辑
      async handleRegister() {
        // 注册表单验证
        if (!this.username || !this.password || !this.confirmPassword) {
          alert('请完善所有必填字段')
          return
        }
        if (this.username.length < 2) {
          alert('用户名至少2个字符')
          return
        }
        if (this.password.length < 6) {
          alert('密码至少6个字符')
          return
        }
        if (this.password !== this.confirmPassword) {
          alert('两次输入的密码不一致')
          return
        }

        this.isLoading = true

        try {
          const res = await registerApi({
            username: this.username,
            password: this.password,
            confirmpassword: this.confirmPassword // 注意：后端 DTO 字段名是 confirmpassword
          })

          if (res.code === 200) {
            alert('注册成功！请登录')
            // 切换回登录模式，清空密码
            this.isRegisterMode = false
            this.password = ''
            this.confirmPassword = ''
          } else {
            alert(res.msg || '注册失败')
          }
        } catch (error) {
          console.error('注册异常:', error)
          alert('网络错误，请稍后重试')
        } finally {
          this.isLoading = false
        }
      },

      // 原有：重置表单（扩展支持注册字段）
      resetForm() {
        this.username = '';
        this.password = '';
        this.confirmPassword = ''; // 新增：重置确认密码
        this.showPassword = false;
      },

      // 原有：键盘回车事件（扩展支持注册模式）
      handleKeyPress(event) {
        if (event.key === 'Enter') {
          // 回车时：注册模式调用注册，登录模式调用登录
          this.isRegisterMode ? this.handleRegister() : this.handleLogin();
        }
      }
    },
    mounted() {
      // 原有：已登录则跳转首页
      if (localStorage.getItem('token')) {
        this.$router.push('/');
      }
      // 原有：绑定键盘回车事件
      window.addEventListener('keydown', this.handleKeyPress);
    },
    beforeUnmount() {
      // 原有：清理键盘事件
      window.removeEventListener('keydown', this.handleKeyPress);
    }
  }
</script>

<style scoped>
.login-container {
  min-height: 100vh;
}

/* 输入框占位符样式 */
:deep(input::placeholder) {
  color: #9ca3af !important;
}
</style>